package com.nsn.das.midas.rest;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

import org.springframework.stereotype.Component;

import com.nsn.das.midas.model.component.Build;
import com.nsn.das.midas.model.component.NetworkElement;
import com.nsn.das.midas.service.BaseManager;
import com.nsn.das.midas.service.assembler.CommonAssembler;
import com.nsn.das.midas.util.ClazzUtils;
import com.nsn.das.utils.CollectionUtils;

@Component
@Path("/")
public class MidasRestService {
	@Resource(name="baseManager")
	private BaseManager baseManager;
	
	@Resource(name="commandClassAssembler")
	private CommonAssembler commonAssembler;
	
	@GET
	@Path("releaseAndBuilds/list/{releasequery}/{buildquery}/{pageIndex}/{pageSize}")
	public Response getReleaseAndBuild(@PathParam("pageIndex") int pageIndex,@PathParam("pageSize") int pageSize
										,@PathParam("releasequery") String releaseQuery,@PathParam("buildquery") String buildQuery){
		try{
			Map<String,Object> conditions =  new HashMap<String,Object>();
			conditions.put("name", buildQuery.equals("null") ? "%" : buildQuery);
			conditions.put("release.name", releaseQuery.equals("null") ? "%" : releaseQuery);
			
			return Response.status(200)
					.entity(commonAssembler.buildBuildsJson(
							CollectionUtils.list2Set(
									baseManager.getEntities(conditions,Build.class,pageIndex,pageSize))))
					.build();
		} catch (Exception e){
			e.printStackTrace();
		}
		
		return Response.status(500).build();
	}
	
	@GET
	@Path("networkElement")
	public Response getNetworkElements(){
		try{
			
			return Response.status(200)
					.entity(commonAssembler.buildNetworkElementJson(
							CollectionUtils.list2Set(
									baseManager.getEntities(
											NetworkElement.class
											,1
											,(int)baseManager.countEntities(NetworkElement.class)))))
					.build();
		} catch (Exception e){
			e.printStackTrace();
		}
		
		return Response.status(500).build();
	}
	
	@POST
	@Path("{clazz}/delete/{id}")
	public Response deleteEntity(@PathParam("id") long id, @PathParam("clazz") String clazz){
		try{
			baseManager.deleteEntity(baseManager.getEntity(ClazzUtils.getClazz(clazz), id));
			return Response.status(200).build();
		} catch (Exception e){
			e.printStackTrace();
		}
		
		return Response.status(500).build();
	}
}
